import axios from 'axios'
import Vue from 'vue'
// 扩展Promise两个方法
window.Promise.prototype.done = function (onFulfilled, onRejected) {
  this.then(onFulfilled, onRejected)
    .catch(function (reason) {
      // 抛出一个全局错误
      setTimeout(() => { throw reason }, 0)
    })
}
window.Promise.prototype.finally = function (callback) {
  let P = this.constructor
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  )
}

// 二期接口
let instance2 = axios.create({
  baseURL: '',
  headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
  // withCredentials: true
})

instance2.interceptors.request.use(
  (config) => {
    // 设置content-type为application/x-www-form-urlencoded时发送数据的格式
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=utf-8') {
      var params = new URLSearchParams()
      if (config.data) {
        for (let i in config.data) {
          if (config.data[i] !== undefined && config.data[i] !== null && config.data[i] !== '') {
            params.append(i, config.data[i])
          }
        }
      }
      config.data = params
    }
    // 设置请求token
    let UBToken = localStorage.getItem('UBToken')
    config.headers && UBToken && (config.headers.UBToken = UBToken)
    return config
  },
  (error) => {
    Vue.prototype.$message({
      type: 'warning',
      message: error.message
    })
  }
)

instance2.interceptors.response.use(
  (res) => {
    // res 拦截器
    if (res.data && res.data.code === -1) {
      // 未登入 或者 登入态失效
      // location.href = '/sys/login';
      // 相关提示信息, 跳转登入页面
      return res
    }
    if (res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code !== 1) {
      // TODO 处理 或者 提示 相应返回失败的结果
      Vue.prototype.$message({
        type: 'warning',
        message: res.data.msgZ
      })
    }
    return res
  },
  (error) => {
    Vue.prototype.$message({
      type: 'warning',
      message: error.message
    })
    // return Promise.reject(error)
  }
)
export { instance2 as axios2 }
